package com.hs.srm.admin.modules.pricemanagement.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hs.srm.admin.common.exception.UnauthorizedException;
import com.hs.srm.admin.common.util.OAConfig;
import com.hs.srm.admin.modules.pricemanagement.entity.InquiryItemEntity;
import com.hs.srm.admin.modules.pricemanagement.entity.InquiryQuotationEntity;
import com.hs.srm.admin.modules.pricemanagement.service.InquiryItemService;
import com.hs.srm.admin.modules.pricemanagement.service.InquiryQuotationService;
import com.hs.srm.admin.modules.pricemanagement.service.ParityService;
import com.hs.srm.admin.modules.pricemanagement.service.impl.ParityServiceImpl;
import com.hs.srm.admin.modules.pricemanagement.vo.InquiryVO;
import com.hs.srm.admin.modules.requisition.service.NproPurchRequestItemService;
import com.hs.srm.admin.modules.requisition.service.ProPurchRequestItemService;
import com.hs.srm.admin.modules.requisition.service.SamplePurchRequestItemService;
import com.hs.srm.admin.modules.sys.controller.AbstractController;
import com.hs.srm.base.common.annotation.SysLog;
import com.hs.srm.base.common.utils.DictDataUtil;
import com.hs.srm.base.common.utils.EntityUtils;
import com.hs.srm.base.modules.sys.entity.SysRoleEntity;
import com.hs.srm.base.modules.sys.entity.SysUserEntity;
import com.hs.srm.base.modules.sys.service.SysRoleService;
import com.hs.srm.common.utils.Constants;
import com.hs.srm.common.utils.PageUtils;
import com.hs.srm.common.utils.R;
import com.landray.kmss.km.review.webservice.Exception_Exception;
import com.landray.kmss.km.review.webservice.IKmReviewWebserviceService;
import com.landray.kmss.km.review.webservice.IKmReviewWebserviceServiceService;
import com.landray.kmss.km.review.webservice.KmReviewParamterForm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import sunnykid.lang.SunnykidDate;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Stream;

/**
 * 报价基本信息
 *
 * @author yanfei
 * @date 2019年3月11日
 */

@RestController
@RequestMapping("/parity")
public class ParityController extends AbstractController {

    private static final long serialVersionUID = -4123823577744890422L;

    // 注入业务层
    @Autowired
    private ParityService parityService;
    // 注入业务层
    @Autowired
    private ParityServiceImpl parityServiceImpl;
    // 注入业务层
    @Autowired
    private InquiryItemService inquiryItemService;
    // 注入业务层
    @Autowired
    private InquiryQuotationService inquiryQuotationService;
    // 注入业务层
    @Autowired
    private NproPurchRequestItemService NPRORequestItemService;

    @Autowired
    private ProPurchRequestItemService proRequestItemService;

    @Autowired
    private SamplePurchRequestItemService sampleItemService;

    @Autowired
    private SysRoleService sysRoleService;

    /**
     * 查询报价单信息
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params, HttpServletRequest resquest) {

        if (resquest.getParameter("poFlag") == null || "".equals(resquest.getParameter("poFlag"))) {
            params.put("poFlag", "NPR");//生产性
        } else {
            params.put("poFlag", resquest.getParameter("poFlag"));
        }
        SysUserEntity username = this.getUser();
        Long userId = username.getUserId();
        List<SysRoleEntity> sysRoleEntities = this.sysRoleService.findRoleName(userId);
        for (SysRoleEntity sysRoleEntity : sysRoleEntities) {
            String roleName = sysRoleEntity.getRoleName();
            if (roleName.equals("采购专员")) {
                String werks = username.getCompanyCode();
                params.put("werks", werks);
            }
        }
        if (username.getDeptId() == 13) {
            params.put("username", username.getUsername());
        }
        // 查询用户列表
        PageUtils page = this.parityService.selectDetailPage(params);
       /* List<InquiryItemEntity> list = (List<InquiryItemEntity>) page.getList();
        list = EntityUtils.valToTxt(list);
        page.setList(list);*/
        return R.ok(page);
    }

    /**
     * 询报价单详情查看
     */
    @RequestMapping("/findById")
    @ResponseBody
    public R findById(@RequestParam(value = "quotationId[]") String[] quotationId) {
        String str = quotationId[0];
        InquiryVO inquiryVO = this.parityService.findbyId(str);
        return R.ok(inquiryVO);
    }

    /**
     * 将报价单传递到OA进行审批
     *
     * @param quotationId
     * @return
     */
    @RequestMapping("/toOa/{quotationId}")
    public R toOa(@PathVariable("quotationId") String quotationId) {

        List<String> quotationIds = Arrays.asList(quotationId.split(","));
        // InquiryQuotationEntity inquiryQuotationEntity = this.inquiryQuotationService.findbyId(quotationId);
        List<InquiryQuotationEntity> inquiryQuotationlist = this.inquiryQuotationService.findbyIds(quotationIds);

        if (inquiryQuotationlist.size() > 0) {
            for (InquiryQuotationEntity inquiryQuotation : inquiryQuotationlist) {
                int stat = inquiryQuotation.getState();
                if (stat == inquiryQuotation.STATE_SHENHETONGGUO) {
                    return R.error("已经审批过了，请勿重复提交！");
                }
                if (stat == inquiryQuotation.STATE_SHENHEZHONG) {
                    return R.error("正在审批中，请勿重复提交！");
                }
            }
        }
        URL wsdlURL = null;
        try {
            wsdlURL = new URL("http://" + OAConfig.host + ":" + OAConfig.port
                    + "/ekp/sys/webservice/kmReviewWebserviceService?wsdl");

        } catch (MalformedURLException ex) {
            return R.error("OA接口地址错误！");
        }
        IKmReviewWebserviceServiceService ss = new IKmReviewWebserviceServiceService(wsdlURL, Constants.SERVICE_NAME);
        IKmReviewWebserviceService port = ss.getIKmReviewWebserviceServicePort();

        KmReviewParamterForm _addReview_arg0;
        //判断是否存在OA账号，为空则返回错误
        try {
            _addReview_arg0 = createForm(inquiryQuotationlist);
        } catch (UnauthorizedException e) {
            return R.error(e.getMessage());
        }

        String _addReview__return = null;
        try {
            _addReview__return = port.addReview(_addReview_arg0); // 启动流程的返回值（流程id）
        } catch (Exception_Exception e) {
            System.out.println("Expected exception: Exception has occurred: " + e.toString());
        }
        if (_addReview__return == null) {
            return R.error("提交OA流程失败！");
        }
        if (inquiryQuotationlist.size() > 0) {
            for (InquiryQuotationEntity inquiryQuotation : inquiryQuotationlist) {
                inquiryQuotation.setState(InquiryQuotationEntity.STATE_SHENHEZHONG);
                inquiryQuotation.setOaDocId(_addReview__return);
                this.inquiryQuotationService.updateById(inquiryQuotation);
            }
        }
        return R.ok();
    }

    /**
     * 报价单添加询价金额
     */
    @SysLog("报价单添加询价金额")
    @RequestMapping(value = "/updateEnquiryPrice", method = RequestMethod.POST)
    @ResponseBody
    public R updateEnquiryPrice(HttpServletRequest resquest) {
        //最终价
        String lastPrice = resquest.getParameter("lastPrice");

        //购买数量
        String purchaseCnt = resquest.getParameter("purchaseCnt");

        //最终价格作为含税价，乘数量计算总价,乘1000是防止价格小数位直接乘 出现精度问题
        double totlePrice = Double.parseDouble(lastPrice) * 1000 * Double.parseDouble(purchaseCnt) / 1000;
        InquiryQuotationEntity quotationEntity = new InquiryQuotationEntity();
        quotationEntity.setQuotationId(resquest.getParameter("quotationId"));
        quotationEntity.setFirstEnquiryPrice(resquest.getParameter("firstPrice"));
        quotationEntity.setSecondEnquiryPrice(resquest.getParameter("secondPrice"));
        quotationEntity.setLastEnquiryPrice(lastPrice);
        //修改含税价为最终价格
        quotationEntity.setPrice(new BigDecimal(lastPrice));
        quotationEntity.setTotalPrice(new BigDecimal(totlePrice));
        boolean result = this.parityService.updateEnquiryPrice(quotationEntity);
        if (!result) {
            return R.error();
        }
        return R.ok(result);
    }


    /**
     * 封装报价单中的各项参数
     *
     * @return KmReviewParamterForm
     */
    /**
     * //流程表单
     * String formValues = "{
     * \"fd_374923e46f5dc4\":\"申请主题\",
     * \"fd_374c406e1ae7be\":\"申请人\",
     * \"fd_374923f22aff68\":\"创建时间\",
     * \"fd_374c406a52eb8e\":\"供应商编码\",
     * \"fd_374c406ce3e690\":\"供应商名称\",
     * \"fd_374c406b98eca6\":\"询价报价单号\",
     * \"fd_374c40741e45d0\":\"报价单ID\",
     * \"fd_374c406f720a6a\":\"净价\",
     * \"fd_374d0c02df18e0\":\"币种\",
     * \"fd_374c4070b307da\":\"物料编码\",
     * \"fd_374c40751ae994\":\"物料描述\",
     * \"fd_374c40793c1b92\":\"数量\",
     * \"fd_374c4071e0a306\":\"价格单位\",
     * \"fd_374c407675aba2\":\"订单单位\",
     * \"fd_374c407a8e47ac\":\"订单价格单位(采购)\",
     * \"fd_374c4072ee404e\":\"总价\",
     * \"fd_374c4077d8d334\":\"税代码\",
     * \"fd_374c407bf76caa\":\"回复交期\",
     * \"fd_374c4072ee404e\":\"第一次询价\",
     * \"fd_374c4077d8d334\":\"第二次询价\",
     * \"fd_374c407bf76caa\":\"最终价\"
     * }
     */
    private KmReviewParamterForm createForm(List<InquiryQuotationEntity> inquiryQuotationlist) {
        // 文档模板id
        KmReviewParamterForm form = new KmReviewParamterForm();
        // 正式系统中的模板id：16a6c5b3754c17fb57b6b51448582ea6
        // 16b1c48e217796f301080674e799a9a8
        //16a524bee617e6d125abfee49f6b7137

        form.setFdTemplateId(OAConfig.parityTemplateId);
        // 文档标题
        form.setDocSubject("物料报价价格审批");

        // 流程发起人
        SysUserEntity user = this.getUser();
        String loginName = user.getOaAccount();
        if (loginName == null || "".equals(loginName)) {
            throw new UnauthorizedException("OA账号为空，请添加OA账号！");
        }
        form.setDocCreator("{\"LoginName\":\"" + loginName + "\"}");
        //测试账号
        //form.setDocCreator("{\"LoginName\":\"2183603\"}");

        // 文档关键字
        form.setFdKeyword("[\"物料\",  \"采购\"]");
        JSONObject formValues = null;
        JSONObject formValuesdetail = null;

        JSONObject finalformValuesdetail = null;

        List<Map<String, Object>> Lists = new ArrayList<Map<String, Object>>();

        /**
         *      模板id：16b2a5702ba9032b9836eb04e5b81934
         * 		明细表id：fd_detail
         * 		询价单id:fd_inquiry_id
         * 		报价单ID:fd_quotation_id
         * 		供应商名称:fd_vendor_name
         * 		物料描述：fd_material_desc
         * 		净价：fd_netprice
         * 		数量：fd_count
         * 		总价：fd_total_price
         * 		订单单位:fd_orderunit
         * 		价格单位:fd_priceunit
         * 		币种:fd_currency
         * 		税码：fd_taxcode
         */
        // **********************2019-06-06yanfei*******************************
        Map<String, List<InquiryQuotationEntity>> map = list4Map(inquiryQuotationlist);
        for (String key : map.keySet()) {
            formValues = new JSONObject();
            formValues.put("fd_inquiry_id", key);// 询价单id
            formValues.put("fd_proposer", this.getUser().getName());// 报价单ID
            formValues.put("fd_area", this.getUser().getCompanyCode());// 工厂地区
            for (InquiryQuotationEntity inquiryQuotationEntity : map.get(key)) {
                formValuesdetail = new JSONObject();
                formValuesdetail.put("fd_detail.fd_quotation_id", inquiryQuotationEntity.getQuotationId());// 报价单ID
                formValuesdetail.put("fd_detail.fd_vendor_name", inquiryQuotationEntity.getVendorName());// 供应商名称
                formValuesdetail.put("fd_detail.fd_material_desc", inquiryQuotationEntity.getMaterialDesc());// 物料描述
                formValuesdetail.put("fd_detail.fd_netprice", inquiryQuotationEntity.getPrice());// 净价
                formValuesdetail.put("fd_detail.fd_count", inquiryQuotationEntity.getPurchaseCnt());// 数量
                formValuesdetail.put("fd_detail.fd_total_price", inquiryQuotationEntity.getTotalPrice());// 总价
                formValuesdetail.put("fd_detail.fd_orderunit", DictDataUtil.valToTxt(inquiryQuotationEntity.getPoUnit(), DictDataUtil.DictType.JLDW));// 订单单位
                formValuesdetail.put("fd_detail.fd_priceunit", DictDataUtil.valToTxt(inquiryQuotationEntity.getPoUnit(), DictDataUtil.DictType.JLDW));// 价格单位
                formValuesdetail.put("fd_detail.fd_currency", inquiryQuotationEntity.getCurrency());// 币种
                formValuesdetail.put("fd_detail.fd_taxcode", inquiryQuotationEntity.getTaxCode());// 税码
                formValuesdetail.put("fd_detail.fd_first_enquiry", inquiryQuotationEntity.getFirstEnquiryPrice());// 第一次询价
                formValuesdetail.put("fd_detail.fd_second_enquiry", inquiryQuotationEntity.getSecondEnquiryPrice());// 第二次询价
                formValuesdetail.put("fd_detail.fd_last_enquiry", inquiryQuotationEntity.getLastEnquiryPrice());// 最终价
                formValuesdetail.put("fd_detail.remark", inquiryQuotationEntity.getRemark());// 备注
                formValuesdetail.put("fd_detail.werks", inquiryQuotationEntity.getWerks());// 工厂
                formValuesdetail
                        .put("fd_detail.fd_reply_delivery_date",
                                SunnykidDate.parseSunnykidDate(inquiryQuotationEntity.getReplyDeliveryDate())
                                        .getStandardDate());
                Map<String, Object> mapTypes = JSON.parseObject(formValuesdetail.toString());
                Lists.add(mapTypes);
            }
        }
        finalformValuesdetail = new JSONObject();
        String strfd_quotation_id[] = new String[Lists.size()];
        String strfd_vendor_name[] = new String[Lists.size()];
        String strfd_material_desc[] = new String[Lists.size()];
        String strfd_netprice[] = new String[Lists.size()];
        String strfd_count[] = new String[Lists.size()];
        String strfd_total_price[] = new String[Lists.size()];
        String strfd_orderunit[] = new String[Lists.size()];
        String strfd_priceunit[] = new String[Lists.size()];
        String strfd_currency[] = new String[Lists.size()];
        String strfd_taxcode[] = new String[Lists.size()];
        String strfd_reply_delivery_date[] = new String[Lists.size()];
        String strfd_first_enquiry[] = new String[Lists.size()];
        String strfd_second_enquiry[] = new String[Lists.size()];
        String strfd_last_enquiry[] = new String[Lists.size()];
        String remark[] = new String[Lists.size()];
        String werks[] = new String[Lists.size()];
        int index = 0;
        for (Map<String, Object> m : Lists) {
            for (String key : m.keySet()) {
                if ("fd_detail.fd_quotation_id".equals(key)) {
                    strfd_quotation_id[index] = (String) m.get(key);
                }
                if ("fd_detail.fd_vendor_name".equals(key)) {
                    strfd_vendor_name[index] = (String) m.get(key);
                }
                if ("fd_detail.fd_material_desc".equals(key)) {
                    strfd_material_desc[index] = (String) m.get(key);
                }
                if ("fd_detail.fd_netprice".equals(key)) {
                    strfd_netprice[index] = (String) m.get(key).toString();
                }
                if ("fd_detail.fd_count".equals(key)) {
                    strfd_count[index] = (String) m.get(key);
                }
                if ("fd_detail.fd_total_price".equals(key)) {
                    strfd_total_price[index] = (String) m.get(key).toString();
                }
                if ("fd_detail.fd_orderunit".equals(key)) {
                    strfd_orderunit[index] = (String) m.get(key);
                }
                if ("fd_detail.fd_priceunit".equals(key)) {
                    strfd_priceunit[index] = (String) m.get(key);
                }
                if ("fd_detail.fd_currency".equals(key)) {
                    strfd_currency[index] = (String) m.get(key);
                }
                if ("fd_detail.fd_taxcode".equals(key)) {
                    strfd_taxcode[index] = (String) m.get(key);
                }
                if ("fd_detail.fd_reply_delivery_date".equals(key)) {
                    strfd_reply_delivery_date[index] = (String) m.get(key);
                }
                if ("fd_detail.fd_first_enquiry".equals(key)) {
                    strfd_first_enquiry[index] = (String) m.get(key);
                }
                if ("fd_detail.fd_second_enquiry".equals(key)) {
                    strfd_second_enquiry[index] = (String) m.get(key);
                }
                if ("fd_detail.fd_last_enquiry".equals(key)) {
                    strfd_last_enquiry[index] = (String) m.get(key);
                }
                if ("fd_detail.remark".equals(key)) {
                    remark[index] = (String) m.get(key);
                }
                if ("fd_detail.werks".equals(key)) {
                    werks[index] = (String) m.get(key);
                }
            }
            index++;
        }
        index = 0;
        finalformValuesdetail.put("fd_detail.fd_quotation_id", strfd_quotation_id);
        finalformValuesdetail.put("fd_detail.fd_vendor_name", strfd_vendor_name);
        finalformValuesdetail.put("fd_detail.fd_material_desc", strfd_material_desc);
        finalformValuesdetail.put("fd_detail.fd_netprice", strfd_netprice);
        finalformValuesdetail.put("fd_detail.fd_count", strfd_count);
        finalformValuesdetail.put("fd_detail.fd_total_price", strfd_total_price);
        finalformValuesdetail.put("fd_detail.fd_orderunit", strfd_orderunit);
        finalformValuesdetail.put("fd_detail.fd_priceunit", strfd_priceunit);
        finalformValuesdetail.put("fd_detail.fd_currency", strfd_currency);
        finalformValuesdetail.put("fd_detail.fd_taxcode", strfd_taxcode);
        finalformValuesdetail.put("fd_detail.fd_reply_delivery_date", strfd_reply_delivery_date);
        finalformValuesdetail.put("fd_detail.fd_first_enquiry", strfd_first_enquiry);
        finalformValuesdetail.put("fd_detail.fd_second_enquiry", strfd_second_enquiry);
        finalformValuesdetail.put("fd_detail.fd_last_enquiry", strfd_last_enquiry);
        finalformValuesdetail.put("fd_detail.remark", remark);
        finalformValuesdetail.put("fd_detail.werks", werks);
        formValues.put("fd_detail", finalformValuesdetail);// 明细表的id
        form.setFormValues(formValues.toJSONString());
        return form;
    }

    /**
     * @param
     * @return Map<Key, List>
     * @description 实现将一个List转化为Map<Key, List>的样式
     */
    public Map<String, List<InquiryQuotationEntity>> list4Map(List<InquiryQuotationEntity> list) {
        Map<String, List<InquiryQuotationEntity>> map = new HashMap<String, List<InquiryQuotationEntity>>();
        if ((list != null) && (list.size() != 0)) {
            for (InquiryQuotationEntity InquiryQuotation : list) {
                List<InquiryQuotationEntity> testList = map.get(InquiryQuotation.getInquiryId()); // 询价单id
                if (testList == null) {
                    testList = new ArrayList<InquiryQuotationEntity>();
                }
                testList.add(InquiryQuotation);
                map.put(InquiryQuotation.getInquiryId(), testList);
            }
        }
        return map;
    }

    /**
     * 比价查看modal更新数据
     */
    @RequestMapping("/updateQuotationById")
    @ResponseBody
    public R updateQuotationById(@RequestParam(value = "quotationId") String quotationId, @RequestParam(value = "priceUnit") String priceUnit
            , @RequestParam(value = "price") String price, @RequestParam(value = "replyDeliveryDate") String replyDeliveryDate) throws ParseException {
        InquiryQuotationEntity quotationEntity = this.inquiryQuotationService.selectById(quotationId);
        quotationEntity.setPrice(new BigDecimal(price));
        quotationEntity.setPriceUnit(priceUnit);
        quotationEntity.setReplyDeliveryDate(new SimpleDateFormat("yyyy-MM-dd").parse(replyDeliveryDate));
        boolean b = this.inquiryQuotationService.updateById(quotationEntity);
        if (b) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 删除
     */
    @SysLog("删除报价单")
    @Transactional
    @RequestMapping("/deleteParity")
    public R deleteParity(@RequestParam(value = "quotationId[]") String[] quotationId) {
        Stream.of(quotationId).forEach((str) -> {
            InquiryItemEntity entity = this.inquiryItemService.selectItemByQuotationId(str);
            this.parityServiceImpl.deleteParity(str);
            //删除报价单恢复请购单为草稿状态
            if (entity.getRequestCode().indexOf("PR") >= 0) {//非生产性
                this.NPRORequestItemService.updateStatus(entity.getRequestCode(), entity.getPurchRequestItemCode());
            } else if (entity.getRequestCode().indexOf("S") >= 0) {//样品
                sampleItemService.updateStatus(entity.getRequestCode(), entity.getPurchRequestItemCode());
            } else {//生产性
                proRequestItemService.updateStatus(entity.getRequestCode(), entity.getPurchRequestItemCode());
            }
        });
        return R.ok();
    }

    /**
     * 修改所有
     */
    @SysLog("修改非生产性购单比价中的详情信息")
    @RequestMapping("/updateAll")
    @ResponseBody
    public R updateAll(String data, String quotationId) {
        InquiryQuotationEntity inquiryQuotationEntity = JSONObject.parseObject(data, InquiryQuotationEntity.class);
        inquiryQuotationEntity.setQuotationId(quotationId);
        this.parityServiceImpl.updateAll(inquiryQuotationEntity);
        return R.msg("更新成功!");
    }
}
